package com.web22_2_1.service.impl;

import com.web22_2_1.entity.User;
import com.web22_2_1.mapper.UserSQL;
import com.web22_2_1.service.UserService;
import com.web22_2_1.utils.DruidDemo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class UserServiceImpl implements UserService {
    @Override
    public User getUser(String username, String password) {
        Connection connection = null;
        PreparedStatement pStatement = null;
        User user = null;
        try {
            connection = DruidDemo.getConnection();
            pStatement = connection.prepareStatement(UserSQL.GET_USER);
            pStatement.setString(1,username);
            pStatement.setString(2,password);
            ResultSet rs = pStatement.executeQuery();
            while(rs.next()){
                user = new User();
                user.setUserId(rs.getInt("UserID"));
                user.setUsername(rs.getString("Username"));
                user.setPassword(rs.getString("Password"));
                user.setEmail(rs.getString("Email"));
                user.setPhone(rs.getString("Phone"));
                user.setCreatedOn(rs.getDate("CreatedOn"));
                user.setLastLogin(rs.getDate("LastLogin"));
            }
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            DruidDemo.destroy(connection, pStatement, null);
        }
        return user;
    }
    @Override
    public boolean addUser(String username, String password, String email, String phone, Date lastLogin) {
        Connection connection = null;
        PreparedStatement pStatement = null;
        int rows = 0;
        try {
            connection = DruidDemo.getConnection();
            pStatement = connection.prepareStatement(UserSQL.ADD_USER);
            pStatement.setString(1,username);
            pStatement.setString(2,password);
            pStatement.setString(3,email);
            pStatement.setString(4,phone);
            pStatement.setDate(5,new java.sql.Date(lastLogin.getTime()));
            rows = pStatement.executeUpdate();
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            DruidDemo.destroy(connection, pStatement, null);
        }
        return rows>0;
    }
}
